package com.qt.myio.pqdata;

import com.qt.myio.entity.Student;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @Author zsf
 * @Date 2023/9/29 15:31
 * @Version 1.0
 */
public class QzRandomDemo01 {

    public static void main(String[] args) throws IOException {

        ArrayList<Student> students = new ArrayList<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("aaa\\names.txt"), "UTF-8"));
        String str;
        while ((str = br.readLine()) != null){
            String[] split = str.split("-");
            students.add(new Student(split[0], split[1], Integer.parseInt(split[2]),Double.parseDouble(split[3])));
        }

        //计算总权重
        double scores = 0D;
        for (Student student : students) {
            scores += student.getScore();
        }


        //计算每个人的权重
        double[] arr = new double[students.size()];
        for (int i = 0; i < students.size(); i++) {
            arr[i] = students.get(i).getScore() / scores;
        }

        //计算权重范围
        for (int i = 1; i < arr.length; i++) {
            arr[i] = arr[i] + arr[i-1];
        }


        //随机抽取
        double random = Math.random();

        //获取 ：    -插入点  - 1  = 结果
        //插入点 = -结果 - 1
        int i = Arrays.binarySearch(arr, random);
        int res = -i - 1;
        Student stuItem = students.get(res);
        stuItem.setScore(stuItem.getScore() / 2);

        BufferedWriter bw = new BufferedWriter(new FileWriter("aaa/names.txt"));

        for (Student student : students) {
            bw.write(student.toString());
            bw.newLine();
        }
        bw.close();

        System.out.println(stuItem);


    }


}
